import { treePermissionForRoleId, updateRole } from '@/services/api/api-admin-role';
import ProForm, { DrawerForm, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { Empty, message } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { useState } from 'react';

interface EditRoleProps {
  role: AdminRoleData.Role;
  onRefurbish: () => void;
}
const EditRole: React.FC<EditRoleProps> = ({ role, onRefurbish }) => {
  /**
   * 初始化树形数据
   */
  const [dataTreePermission, setDataTreePermissionState] = useState<DataNode[]>();
  const [dataCheckTreePermission, setDataCheckTreePermissionState] = useState<React.Key[]>();
  let checkTreeKeys;

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminPermissionData.Permission[]): any {
    const treeData = new Array();

    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          children: readyTreeData(val.children as AdminPermissionData.Permission[]),
        });
        if (val.checked && !val.children) {
          checkTreeKeys.push(val.id);
        }
      });
    }
    return treeData;
  }

  /**
   * 加载组织树请求网络
   */
  const loadRoleTreePermissionData = async (id: string) => {
    try {
      const response = await treePermissionForRoleId({ id });

      if (response.code === 0) {
        checkTreeKeys = new Array();

        const treeData = new Array<DataNode>();

        if (response.data.length !== 0) {
          treeData.push({
            title: '五媒协同',
            key: '0',
            children: readyTreeData(response.data),
          });
        }

        setDataTreePermissionState(treeData);

        setDataCheckTreePermissionState(checkTreeKeys);
      }
    } catch (error) { }
  };

  return (
    <DrawerForm
      key="edit_role"
      title="编辑角色"
      drawerProps={{
        destroyOnClose: true,
      }}
      initialValues={{
        name: role.name,
        describes: role.describes,
        state: role.state,
      }}
      trigger={<a key="edit">编辑</a>}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          loadRoleTreePermissionData(role.id);
        }
      }}
      onFinish={async (values) => {
        const response = await updateRole({
          id: role.id,
          permissionIds: dataCheckTreePermission,
          ...values,
        });
        if (response.code === 0) {
          message.success('提交成功');
        }
        onRefurbish();
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="name"
          label="名称"
          rules={[{ required: true, message: '请输入名称' }]}
        />
        <ProFormText width="md" name="describes" label="描述" />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormRadio.Group
          name="state"
          label="状态"
          options={[
            {
              label: '启用',
              value: 1,
            },
            {
              label: '禁用',
              value: 0,
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        {dataTreePermission && dataTreePermission.length ? (
          <Tree
            defaultExpandAll
            treeData={dataTreePermission}
            checkedKeys={dataCheckTreePermission}
            checkable
            onCheck={(checked: any) => {
              setDataCheckTreePermissionState(checked);
            }}
          />
        ) : (
          <Empty />
        )}
      </ProForm.Group>
    </DrawerForm>
  );
};
export default EditRole;
